package com.example.basic.web.service.newly.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.basic.base.impl.BaseEntityServiceImpl;
import com.example.basic.exception.ServiceException;
import com.example.basic.utils.HttpUtils;
import com.example.basic.utils.IdUtils;
import com.example.basic.utils.ObjectUtils;
import com.example.basic.web.enums.DeviceStatusEnum;
import com.example.basic.web.mapper.device.DeviceMapper;
import com.example.basic.web.mapper.newly.*;
import com.example.basic.web.mapper.zoneDepot.ZoneDepotMapper;
import com.example.basic.web.model.device.Device;
import com.example.basic.web.model.newly.*;
import com.example.basic.web.model.zoneDepot.ZoneDepot;
import com.example.basic.web.request.AddFlowDto;
import com.example.basic.web.request.GetDeviceDto;
import com.example.basic.web.request.HandMoveDto;
import com.example.basic.web.request.UserAffirmDto;
import com.example.basic.web.service.newly.ISysPdaFlowService;
import com.example.basic.web.webSocket.WebSocketServerUtil;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 流程Service业务层处理
 *
 * @author zhiyun
 * @date 2025-08-08
 */
@Slf4j
@Service
public class SysPdaFlowServiceImpl extends BaseEntityServiceImpl<SysPdaFlowMapper, SysPdaFlow> implements ISysPdaFlowService
{
    @Autowired
    private SysPdaFlowMapper sysPdaFlowMapper;

    @Autowired
    private SysBacklogMapper sysBacklogMapper;

    @Autowired
    private ZoneDepotMapper zoneDepotMapper;

    @Autowired
    private DeviceMapper  deviceMapper;

    @Autowired
    private SysFlowTaskMapper sysFlowTaskMapper;

    @Autowired
    private SysHandMoveMapper sysHandMoveMapper;

    @Autowired
    private SysAdmireMapper sysAdmireMapper;

    /**
     * 无状态
     */
    public static final Integer FLOW_STATUS_NULL = 0;

    /**
     * 待确认
     */
    public static final Integer FLOW_STATUS_WAIT_SURE = 1;

    /**
     * 已确认
     */
    public static final Integer FLOW_STATUS_SURE = 2;


    /**
     * 否
     */
    public static final Integer FLOW_STATUS_NO = 0;

    /**
     * 是
     */
    public static final Integer FLOW_STATUS_YES = 1;

    /**
     * 今日
     */
    public static final Integer FIRE_TYPE_TODAY= 1;

    /**
     * 择日
     */
    public static final Integer FIRE_TYPE_OTHER= 2;


    @Override
    public Boolean add(AddFlowDto addFlowDto) {
        LambdaQueryWrapper<SysPdaFlow> flowLambdaQueryWrapper=new LambdaQueryWrapper<>();
        flowLambdaQueryWrapper.eq(SysPdaFlow::getRemainsId,addFlowDto.getRemainsId());
        SysPdaFlow sysPdaFlows = sysPdaFlowMapper.selectOne(flowLambdaQueryWrapper);
        if (ObjectUtil.isNotEmpty(sysPdaFlows)){
            throw new ServiceException("流程信息已录入,请勿重复录入");
        }
        SysPdaFlow sysPdaFlow = BeanUtil.toBean(addFlowDto, SysPdaFlow.class);
        //初次录入视为进入初次信息确认阶段
        sysPdaFlow.setMsgFirstAffirm(FLOW_STATUS_WAIT_SURE);
        sysPdaFlow.setDisinfectStatus(FLOW_STATUS_NULL);
        //判断是否需要冰柜 火化类型为今日的话不再进入冰柜 选择择日的话进入冰柜
        if (addFlowDto.getFireType().equals(FIRE_TYPE_TODAY)){
            //今日火化 无需进入冰柜
            sysPdaFlow.setIsFreezer(FLOW_STATUS_NO);
        }else {
            //择日火化 需要进入冰柜
            sysPdaFlow.setIsFreezer(FLOW_STATUS_YES);
            sysPdaFlow.setFreezerStatus(addFlowDto.getFreezerType());
            sysPdaFlow.setFreezerType(addFlowDto.getFreezerType());
        }
        //判断瞻仰厅选择的使用的时间是否已经被占用
        if (addFlowDto.getIsAdmire().equals(FLOW_STATUS_YES)) {
            //查询今日此瞻仰厅的预约人数
            LambdaQueryWrapper<SysPdaFlow> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysPdaFlow::getAdmireId, addFlowDto.getAdmireId());
            queryWrapper.apply("DATE(create_at) = CURDATE()");
            Integer i = sysPdaFlowMapper.selectCount(queryWrapper);

            SysAdmire sysAdmire = sysAdmireMapper.selectById(addFlowDto.getAdmireId());
            if (i >= sysAdmire.getUsableSessionNum()){
                throw new ServiceException("该瞻仰厅今日预约场次已满,请重新选择");
            }
        }

        //当前状态 1暂存区 2消毒 3 spa 4冰柜 5化妆 6二次信息确认 7瞻仰 8火化
        //信息录入 则当前状态为1该轮到初次确认了,也就是暂存区
        sysPdaFlow.setNowStage(1);
        sysPdaFlow.setCreateAt(new Date());
        sysPdaFlow.setUpdateAt(new Date());
        sysPdaFlow.setId(IdUtils.fastUUID());
        sysPdaFlow.setPositionId(addFlowDto.getDeviceId());
        //选择一个空余的库位
//        LambdaQueryWrapper<ZoneDepot> zoneDepotLambdaQueryWrapper=new LambdaQueryWrapper<>();
//        zoneDepotLambdaQueryWrapper.eq(ZoneDepot::getIsUse,"0");
//        List<ZoneDepot> zoneDepots = zoneDepotMapper.selectList(zoneDepotLambdaQueryWrapper);
//
//        if (!zoneDepots.isEmpty()){
//            ZoneDepot zoneDepot = zoneDepots.get(0);
//            sysPdaFlow.setPositionId(zoneDepot.getId());
//            zoneDepot.setIsUse("1");
//            zoneDepotMapper.updateById(zoneDepot);
//        }


        sysPdaFlowMapper.insert(sysPdaFlow);

        //往初次录入的人工表中插入数据
        String taskRecordId = IdUtils.fastUUID();
        LambdaQueryWrapper<Device> deviceLambdaQueryWrapper=new LambdaQueryWrapper<>();;
        deviceLambdaQueryWrapper.eq(Device::getId,addFlowDto.getDeviceId());
        Device device = deviceMapper.selectOne(deviceLambdaQueryWrapper);
        //选择一个空闲的在暂存区的设备

        LambdaQueryWrapper<Device> deviceEnd=new LambdaQueryWrapper<>();
        deviceEnd.eq(Device::getDeviceType,2);
        deviceEnd.eq(Device::getEnableFlag,1);
        deviceEnd.eq(Device::getStatus,1);
        deviceEnd.orderByAsc(Device::getSortNo);
        List<Device> devices = deviceMapper.selectList(deviceEnd);
        if (devices.isEmpty()){
            throw new ServiceException("暂无空闲的在暂存区的设备");
        }

        Device endDevice = devices.get(0);
        try {
            //将两台设备都置为忙碌
            endDevice.setStatus(DeviceStatusEnum.work.getType());
            device.setStatus(DeviceStatusEnum.work.getType());
            device.setUpdateAt(new Date());
            endDevice.setUpdateAt(new Date());
            deviceMapper.updateById( device);
            deviceMapper.updateById(endDevice);

            SysFlowTask task =new SysFlowTask();
            task.setId(taskRecordId);
            task.setFlowId(sysPdaFlow.getId());
            task.setStartPositionId(device.getId());
            task.setEndPositionId(endDevice.getId());
            task.setStartStatus(0);
            task.setEndStatus(0);
            task.setCreateAt(new Date());
            task.setUpdateAt(new Date());
            //到暂存区的 当前状态0信息录入 1暂存区 2消毒 3 spa 4冰柜 5化妆 6二次信息确认 7瞻仰 8火化
            task.setNowStage(0);
            sysFlowTaskMapper.insert(task);

            HttpUtils.sendPost(null,device.getDevicePoint(),endDevice.getDevicePoint(),taskRecordId);
        } catch (IOException e) {
            throw new ServiceException("调度失败请联系管理员");
        }


//        SysBacklog sysBacklog = new SysBacklog();
//        sysBacklog.setFlowId(sysPdaFlow.getId());
//        sysBacklog.setSysUserId("308007ce-f0ca-4c11-8057-5703699c6e7e");
//        sysBacklog.setCreateAt(new Date());
//        sysBacklog.setUpdateAt(new Date());
//        sysBacklog.setStatus(FLOW_STATUS_NO);
//        sysBacklog.setId(IdUtils.fastUUID());
//        sysBacklogMapper.insert(sysBacklog);
//
//        WebSocketServerUtil.sendInfo("来新任务了","308007ce-f0ca-4c11-8057-5703699c6e7e");




        return true;
    }

    /**
     * 确认
     * @param userAffirmDto
     * @return
     * 阶段:当前状态 1暂存区(初次确认) 2消毒 3 spa 4冰柜 5化妆 6二次信息确认 7瞻仰 8火化 9完成
     * */
    @Override
    public Boolean affirm(UserAffirmDto userAffirmDto) {
        SysPdaFlow sysPdaFlow = sysPdaFlowMapper.selectById(userAffirmDto.getFlowId());

//        if (!userAffirmDto.getPositionId().equals(sysPdaFlow.getPositionId())){
//            //证明位置发生了变化
//            ZoneDepot zoneDepot = zoneDepotMapper.selectById(sysPdaFlow.getPositionId());
//            if (ObjectUtil.isNotEmpty(zoneDepot)) {
//                zoneDepot.setIsUse("0");
//                zoneDepotMapper.updateById(zoneDepot);
//            }
//
//            sysPdaFlow.setPositionId(userAffirmDto.getPositionId());
//        }

        //将确认的待办视为完成
        SysBacklog backlog = sysBacklogMapper.selectById(userAffirmDto.getBackLogId());
        backlog.setStatus(FLOW_STATUS_YES);
        backlog.setUpdateAt(new Date());
        sysBacklogMapper.updateById(backlog);

        Integer nowStage = sysPdaFlow.getNowStage();

        switch (nowStage){
            case 1:
                //初次确认进入下一步消毒 消毒现在不一定是必须得
                //判断是否需要消毒
                if (sysPdaFlow.getIsDisinfect().equals(FLOW_STATUS_YES)){
                    sysPdaFlow.setNowStage(2);
                    sysPdaFlow.setUpdateAt(new Date());
                    sysPdaFlow.setDisinfectStatus(FLOW_STATUS_WAIT_SURE);
                    sysPdaFlow.setMsgFirstAffirm(FLOW_STATUS_SURE);
                    addJob(sysPdaFlow,3,1);
                } else if (sysPdaFlow.getIsSpa().equals(FLOW_STATUS_YES)){
                    //需要spa
                    sysPdaFlow.setNowStage(3);
                    sysPdaFlow.setUpdateAt(new Date());
                    sysPdaFlow.setSpaStatus(FLOW_STATUS_WAIT_SURE);
                    addJob(sysPdaFlow,4,2);
                }else if (sysPdaFlow.getIsMake().equals(FLOW_STATUS_YES)){
                    //需要化妆
                    sysPdaFlow.setNowStage(5);
                    sysPdaFlow.setUpdateAt(new Date());
                    sysPdaFlow.setMakeStatus(FLOW_STATUS_WAIT_SURE);
                    addJob(sysPdaFlow,5,4);
                }else{
                    //spa和化妆都没有的话,直接进入二次确认
                    sysPdaFlow.setNowStage(6);
                    sysPdaFlow.setUpdateAt(new Date());
                    sysPdaFlow.setMsgSecondAffirm(FLOW_STATUS_WAIT_SURE);
                    addJob(sysPdaFlow,2,6);
                }
                break;
            case 2:
                sysPdaFlow.setDisinfectStatus(FLOW_STATUS_SURE);
                //消毒已经确认 进入下一步spa,先判断客户是否需要spa
                if (sysPdaFlow.getIsSpa().equals(FLOW_STATUS_YES)){
                    //需要spa
                    sysPdaFlow.setNowStage(3);
                    sysPdaFlow.setUpdateAt(new Date());
                    sysPdaFlow.setSpaStatus(FLOW_STATUS_WAIT_SURE);
                    addJob(sysPdaFlow,4,2);
                }else if (sysPdaFlow.getIsMake().equals(FLOW_STATUS_YES)){
                    //需要化妆
                    sysPdaFlow.setNowStage(5);
                    sysPdaFlow.setUpdateAt(new Date());
                    sysPdaFlow.setMakeStatus(FLOW_STATUS_WAIT_SURE);
                    addJob(sysPdaFlow,5,4);
                }else{
                    //spa和化妆都没有的话,直接进入二次确认
                    sysPdaFlow.setNowStage(6);
                    sysPdaFlow.setUpdateAt(new Date());
                    sysPdaFlow.setMsgSecondAffirm(FLOW_STATUS_WAIT_SURE);
                    addJob(sysPdaFlow,2,6);
                }
                break;
            case 3:
                    sysPdaFlow.setSpaStatus(FLOW_STATUS_SURE);
                    //spa已经确认 进入下一步化妆,先判断客户是否需要化妆
                    if (sysPdaFlow.getIsMake().equals(FLOW_STATUS_YES)) {
                        //需要化妆
                        sysPdaFlow.setNowStage(5);
                        sysPdaFlow.setUpdateAt(new Date());
                        sysPdaFlow.setMakeStatus(FLOW_STATUS_WAIT_SURE);
                        addJob(sysPdaFlow,5,4);
                    } else {
                        //spa和化妆都没有的话,直接进入二次确认
                        sysPdaFlow.setNowStage(6);
                        sysPdaFlow.setUpdateAt(new Date());
                        sysPdaFlow.setMsgSecondAffirm(FLOW_STATUS_WAIT_SURE);
                        addJob(sysPdaFlow,2,6);
                    }
                    break;
            case 5:
                sysPdaFlow.setMakeStatus(FLOW_STATUS_SURE);
                //化妆已经确认 进入下一步二次确认
                sysPdaFlow.setNowStage(6);
                sysPdaFlow.setUpdateAt(new Date());
                sysPdaFlow.setMsgSecondAffirm(FLOW_STATUS_WAIT_SURE);
                addJob(sysPdaFlow,2,6);
                break;
            case 6:
                sysPdaFlow.setMsgSecondAffirm(FLOW_STATUS_SURE);
                //二次确认已经确认 进入下一步 瞻仰 判断是否需要瞻仰
                if (sysPdaFlow.getIsAdmire().equals(FLOW_STATUS_YES)){
                    //需要瞻仰
                    sysPdaFlow.setNowStage(7);
                    sysPdaFlow.setUpdateAt(new Date());
                    sysPdaFlow.setAdmireStatus(FLOW_STATUS_WAIT_SURE);
                    //新增下一个瞻仰阶段的待办,先判断瞻仰是否被占用 如果被占用的话 先到瞻仰前缓存
                    Device endDevice=deviceMapper.selectById(sysPdaFlow.getAdmireId());
                    if (endDevice.getStatus().equals(DeviceStatusEnum.work.getType())){
                        //如果被占用的话 先到瞻仰前缓存 同时判断瞻仰厅缓存是否也被占用 如果被占用的话 提示
                        SysAdmire sysAdmire = sysAdmireMapper.selectById(sysPdaFlow.getAdmireId());
                        Device device = deviceMapper.selectById(sysAdmire.getCachePositionId());
                        if (device.getStatus().equals(DeviceStatusEnum.work.getType())){
                            throw new ServiceException("该告别厅提升机与该提升机接驳台均被占用,请稍后再试");
                        }else {
                            addJob(sysPdaFlow, 13, 17);
                        }
                    }else {
                        addJob(sysPdaFlow, 6, 7);
                    }
                }else {
                    //不需要瞻仰 直接进入火化
                    sysPdaFlow.setNowStage(8);
                    sysPdaFlow.setUpdateAt(new Date());
                    sysPdaFlow.setFireStatus(FLOW_STATUS_WAIT_SURE);
                    //新增下一个火化阶段的待办,直接新增到火化
//                    LambdaQueryWrapper<Device> queryWrapper=new LambdaQueryWrapper<>();
//                    queryWrapper.eq(Device::getDeviceType,14);
//                    queryWrapper.eq(Device::getEnableFlag,1);
//                    queryWrapper.eq(Device::getStatus,1);
//                    List<Device> deviceList = deviceMapper.selectList(queryWrapper);
//                    if (deviceList.isEmpty()){
//                        //证明没有空闲的火化区 先到火化前缓存
//                        LambdaQueryWrapper<Device> deviceLambdaQueryWrapper=new LambdaQueryWrapper<>();
//                        deviceLambdaQueryWrapper.eq(Device::getDeviceType,14);
//                        deviceLambdaQueryWrapper.eq(Device::getEnableFlag,1);
//                        deviceLambdaQueryWrapper.eq(Device::getStatus,1);
//                        List<Device> devices = deviceMapper.selectList(deviceLambdaQueryWrapper);
//                        if (devices.isEmpty()){
//                            throw new ServiceException("该负一负二提升机与担架板缓存接驳台均被占用,请稍后再试");
//                        }else {
//                            addJob(sysPdaFlow, 14, 18);
//                        }
//                    }else {
                        addJob(sysPdaFlow,10,10);
//                    }
                }
                break;
            case 7:
                sysPdaFlow.setAdmireStatus(FLOW_STATUS_SURE);
                //瞻仰已经确认 进入下一步 火化
                sysPdaFlow.setNowStage(8);
                sysPdaFlow.setUpdateAt(new Date());
                sysPdaFlow.setFireStatus(FLOW_STATUS_WAIT_SURE);

//                //先查询火化区是否有空闲 有空闲的话直接去火化区 没有空闲的话 先到火化前缓存
//                LambdaQueryWrapper<Device> queryWrapper=new LambdaQueryWrapper<>();
//                queryWrapper.eq(Device::getDeviceType,14);
//                queryWrapper.eq(Device::getEnableFlag,1);
//                queryWrapper.eq(Device::getStatus,1);
//                List<Device> deviceList = deviceMapper.selectList(queryWrapper);
//                if (deviceList.isEmpty()){
//                    //证明没有空闲的火化区 先到火化前缓存
//                    addJob(sysPdaFlow,14,18);
//                }else {
                    addJob(sysPdaFlow,10,10);
//                }

                break;
            case 8:
                    //火化已经确认 完成
                sysPdaFlow.setNowStage(9);
                sysPdaFlow.setFireStatus(FLOW_STATUS_SURE);
                sysPdaFlow.setUpdateAt(new Date());
                sysPdaFlow.setFireTime(new Date());
                //添加任务 从火花间到中专提升机
                //先判断中转台是否空闲 有空闲的话直接发往负一负二提升机,没有空闲的话 先到中转接驳台

                LambdaQueryWrapper<Device> deviceLambdaQueryWrapper=new LambdaQueryWrapper<>();
                deviceLambdaQueryWrapper.eq(Device::getDeviceType,10);
                deviceLambdaQueryWrapper.eq(Device::getEnableFlag,1);
                deviceLambdaQueryWrapper.eq(Device::getStatus,1);
                List<Device> devices = deviceMapper.selectList(deviceLambdaQueryWrapper);
                if (devices.isEmpty()){
                    //证明没有空闲的负一负二中转接驳台 先到担架板缓存中转接驳台
                    addJob(sysPdaFlow,15,19);
                }else {
                    //到担架板缓存接驳台
                    addJob(sysPdaFlow, 10, 11);
                }
                break;
            default:
                throw new ServiceException("流程异常");
        }
        sysPdaFlowMapper.updateById(sysPdaFlow);
        return true;
    }

    @Override
    public Boolean getDj(String positionId) {
//        Device device = deviceMapper.selectById(positionId);

        //获取状态为3的,状态为3证明上面已被占用是有但加班的

        LambdaQueryWrapper<Device> deviceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        deviceLambdaQueryWrapper.eq(Device::getDeviceType, 11);
        deviceLambdaQueryWrapper.eq(Device::getEnableFlag, 1);
        deviceLambdaQueryWrapper.eq(Device::getStatus, 3);
        deviceLambdaQueryWrapper.orderByAsc(Device::getDeviceCode);
        List<Device> djDeviceList = deviceMapper.selectList(deviceLambdaQueryWrapper);
        if (djDeviceList.isEmpty()) {
            throw new ServiceException("暂无空闲的担架板");
        }

        Device dj = djDeviceList.get(0);
        String uuid = IdUtils.fastUUID();

        try {

//            dj.setStatus("3");
//            dj.setUpdateAt(new Date());
//            deviceMapper.updateById(dj);

            LambdaQueryWrapper<Device> devQueryWrapper = new LambdaQueryWrapper<>();
            devQueryWrapper.eq(Device::getDeviceType, 12);
            devQueryWrapper.eq(Device::getEnableFlag, 1);
            devQueryWrapper.eq(Device::getStatus, 1);
            devQueryWrapper.orderByAsc(Device::getDeviceCode);
            List<Device> deviceList = deviceMapper.selectList(devQueryWrapper);
            if (deviceList.isEmpty()){
                throw new ServiceException("当前担架板中转接驳台被占用");
            }
            Device zz = deviceList.get(0);

            SysFlowTask task =new SysFlowTask();
            task.setId(uuid);
            task.setFlowId(null);
            task.setStartPositionId(dj.getId());
            task.setEndPositionId(zz.getId());
            task.setStartStatus(0);
            task.setEndStatus(0);
            task.setCreateAt(new Date());
            task.setUpdateAt(new Date());
            task.setTargetPosition(positionId);
            //到暂存区的 当前状态 0 信息录入 1暂存区 2消毒 3 spa 4 冰柜 5化妆 6二次信息确认 7瞻仰 8火化
            task.setNowStage(13);
            sysFlowTaskMapper.insert(task);

            zz.setStatus("3");
            zz.setUpdateAt(new Date());
            deviceMapper.updateById(zz);


            HttpUtils.sendPost(null, dj.getDevicePoint(), zz.getDevicePoint(),uuid);
        } catch (IOException e) {
            throw new ServiceException("调度失败请联系管理员");
        }
        return true;
    }


    public void  addJob(SysPdaFlow sysPdaFlow,Integer deviceType,Integer stage){
        Device device = deviceMapper.selectById(sysPdaFlow.getPositionId());
        Device endDevice=null;
        if (deviceType==6){
            endDevice=deviceMapper.selectById(sysPdaFlow.getAdmireId());
        }else if (deviceType==13) {
            SysAdmire sysAdmire = sysAdmireMapper.selectById(sysPdaFlow.getAdmireId());
            endDevice = deviceMapper.selectById(sysAdmire.getCachePositionId());
        }else {
            LambdaQueryWrapper<Device> deviceEnd = new LambdaQueryWrapper<>();
            deviceEnd.eq(Device::getDeviceType, deviceType);
            deviceEnd.eq(Device::getEnableFlag, 1);
            deviceEnd.eq(Device::getStatus, 1);
            deviceEnd.orderByDesc(Device::getSortNo);
            List<Device> devices = deviceMapper.selectList(deviceEnd);
            if (devices.isEmpty()) {
                throw new ServiceException("暂无空闲的设备");
            }
            endDevice = devices.get(0);
        }
        try {

            String taskRecordId = IdUtils.fastUUID();
            //将两台设备都置为忙碌
            endDevice.setStatus(DeviceStatusEnum.work.getType());
            endDevice.setUpdateAt(new Date());
            deviceMapper.updateById(endDevice);

            SysFlowTask task =new SysFlowTask();
            task.setId(taskRecordId);
            task.setFlowId(sysPdaFlow.getId());
            task.setStartPositionId(sysPdaFlow.getPositionId());
            task.setEndPositionId(endDevice.getId());
            task.setStartStatus(0);
            task.setEndStatus(0);
            task.setCreateAt(new Date());
            task.setUpdateAt(new Date());
            //到暂存区的 当前状态0信息录入 1暂存区 2消毒 3 spa 4冰柜 5化妆 6二次信息确认 7瞻仰 8火化
            task.setNowStage(stage);
            sysFlowTaskMapper.insert(task);

            HttpUtils.sendPost(null,device.getDevicePoint(),endDevice.getDevicePoint(),taskRecordId);
        } catch (IOException e) {
            throw new ServiceException("调度失败请联系管理员");
        }
    }

    public void addBacklog(String flowId,String userId){
        SysBacklog sysBacklog = new SysBacklog();
        sysBacklog.setFlowId(flowId);
        sysBacklog.setSysUserId(userId);
        sysBacklog.setCreateAt(new Date());
        sysBacklog.setUpdateAt(new Date());
        sysBacklog.setStatus(FLOW_STATUS_NO);
        sysBacklog.setId(IdUtils.fastUUID());
        sysBacklogMapper.insert(sysBacklog);
    }

    @Override
    public List<Device> getDevice(GetDeviceDto deviceDto) {
        LambdaQueryWrapper<Device> deviceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        deviceLambdaQueryWrapper.eq(Device::getDeviceType, deviceDto.getType());
        deviceLambdaQueryWrapper.eq(Device::getEnableFlag, 1);
        deviceLambdaQueryWrapper.like(Device::getDeviceName,deviceDto.getDeviceName());
        deviceLambdaQueryWrapper.orderByAsc(Device::getDeviceCode);

        return deviceMapper.selectList(deviceLambdaQueryWrapper);
    }

    @Override
    public Boolean handMove(HandMoveDto handMoveDto) {
        Device startDevice = deviceMapper.selectById(handMoveDto.getStartPositionId());
        Device endDevice = deviceMapper.selectById(handMoveDto.getEndPositionId());

        SysHandMove sysHandMove = new SysHandMove();
        String handMoveId = IdUtils.fastUUID();
        sysHandMove.setId(handMoveId);
        sysHandMove.setFlowId(handMoveDto.getFlowId());
        sysHandMove.setStartPosition(handMoveDto.getStartPositionId());
        sysHandMove.setEndPosition(handMoveDto.getEndPositionId());

        if (startDevice.getDeviceType().equals("1")||startDevice.getDeviceType().equals("2")||startDevice.getDeviceType().equals("3")
                ||startDevice.getDeviceType().equals("4")||startDevice.getDeviceType().equals("5")||startDevice.getDeviceType().equals("6")){
            //需要中转
            if (endDevice.getDeviceType().equals("11")){
                //担架板中转
                sysHandMove.setFirstTransferPosition("12");
            }else if (endDevice.getDeviceType().equals("7")){
                //负一负二中转
                sysHandMove.setFirstTransferPosition("10");
            }

        }else if (startDevice.getDeviceType().equals("11")) {
            if (endDevice.getDeviceType().equals("1") || endDevice.getDeviceType().equals("2") || endDevice.getDeviceType().equals("3")
                    || endDevice.getDeviceType().equals("4") || endDevice.getDeviceType().equals("5") || endDevice.getDeviceType().equals("6")) {
                //担架板中转
                sysHandMove.setFirstTransferPosition("12");
            }
        }else if (startDevice.getDeviceType().equals("7")) {
            if (endDevice.getDeviceType().equals("1") || endDevice.getDeviceType().equals("2") || endDevice.getDeviceType().equals("3")
                    || endDevice.getDeviceType().equals("4") || endDevice.getDeviceType().equals("5") || endDevice.getDeviceType().equals("6")) {
                //负一负二中转
                sysHandMove.setFirstTransferPosition("10");
            }else if (endDevice.getDeviceType().equals("11")){
                //负一负二中转 再担架板中转
                sysHandMove.setFirstTransferPosition("10");
                sysHandMove.setSecondTransferPosition("12");
            }
        }
        sysHandMove.setCreateAt(new Date());
        sysHandMove.setUpdateAt(new Date());
        sysHandMove.setStage(1);
        sysHandMoveMapper.insert(sysHandMove);

        //下发第一个任务
        String uuid = IdUtils.fastUUID();
        try {
            SysFlowTask task =new SysFlowTask();
            task.setId(uuid);
            if (ObjectUtil.isNotEmpty(handMoveDto.getFlowId())){
                task.setFlowId(handMoveDto.getFlowId());
            }
            task.setStartPositionId(startDevice.getId());
            //判断第一步的终点位置
            String endpoint;
            if (ObjectUtil.isNotEmpty(sysHandMove.getFirstTransferPosition())){
                //判断中转点是否空闲
                LambdaQueryWrapper<Device> deviceLambdaQueryWrapper=new LambdaQueryWrapper<>();
                deviceLambdaQueryWrapper.eq(Device::getDeviceType,sysHandMove.getFirstTransferPosition());
                deviceLambdaQueryWrapper.eq(Device::getEnableFlag,1);
                deviceLambdaQueryWrapper.eq(Device::getStatus,1);
                List<Device> devices = deviceMapper.selectList(deviceLambdaQueryWrapper);

                if (devices.isEmpty()){
                    throw new ServiceException("暂无空闲的中转设备");
                }
                Device device = devices.get(0);
                task.setEndPositionId(device.getId());
                endpoint=device.getDevicePoint();
            }else {
                //不需要中转直接到终点 判断终点是否空闲
                if (endDevice.getStatus().equals(DeviceStatusEnum.work.getType())){
                    throw new ServiceException("目标正在使用中");
                }
                task.setEndPositionId(endDevice.getId());
                endpoint=endDevice.getDevicePoint();
            }
            task.setStartStatus(0);
            task.setEndStatus(0);
            task.setCreateAt(new Date());
            task.setUpdateAt(new Date());
            task.setNowStage(15);
            task.setHandMoveId(handMoveId);
            sysFlowTaskMapper.insert(task);

            HttpUtils.sendPost(null, startDevice.getDevicePoint(), endpoint,uuid);

            //然后将其实和终止都设为使用中
            LambdaUpdateWrapper <Device> deviceLambdaUpdateWrapper=new LambdaUpdateWrapper<>();
            deviceLambdaUpdateWrapper.in(Device::getDevicePoint,startDevice.getDevicePoint(),endpoint);
            deviceLambdaUpdateWrapper.set(Device::getStatus,DeviceStatusEnum.work.getType());
            deviceLambdaUpdateWrapper.set(Device::getUpdateAt,new Date());
            deviceMapper.update(null,deviceLambdaUpdateWrapper);

        } catch (IOException e) {
            throw new ServiceException("调度失败请联系管理员");
        }

        return true;


    }

    /**
     * 流程干预
     * @param sysPdaFlow
     * @return
     */
    @Override
    public Boolean updateFlow(SysPdaFlow sysPdaFlow) {
        SysPdaFlow flow = sysPdaFlowMapper.selectById(sysPdaFlow.getId());

        flow.setUpdateAt(new Date());

        //消毒
        if (flow.getIsDisinfect().equals(FLOW_STATUS_YES)&&sysPdaFlow.getIsDisinfect().equals(FLOW_STATUS_NO)) {
            //消毒由是改为不是
            flow.setIsDisinfect(FLOW_STATUS_NO);
        } else if (flow.getIsDisinfect().equals(FLOW_STATUS_NO)&&sysPdaFlow.getIsDisinfect().equals(FLOW_STATUS_YES)){
            //消毒由不是改为是
            flow.setIsDisinfect(FLOW_STATUS_YES);
        }

        //spa
        if (flow.getIsSpa().equals(FLOW_STATUS_YES)&&sysPdaFlow.getIsSpa().equals(FLOW_STATUS_NO)) {
            //spa由是改为不是
            flow.setIsSpa(FLOW_STATUS_NO);
        }else if (flow.getIsSpa().equals(FLOW_STATUS_NO)&&sysPdaFlow.getIsSpa().equals(FLOW_STATUS_YES)){
            //spa由不是改为是
            flow.setIsSpa(FLOW_STATUS_YES);
        }

        //化妆
        if (flow.getIsMake().equals(FLOW_STATUS_YES) && sysPdaFlow.getIsMake().equals(FLOW_STATUS_NO)) {
            flow.setIsMake(FLOW_STATUS_NO);
        }else if (flow.getIsMake().equals(FLOW_STATUS_NO) && sysPdaFlow.getIsMake().equals(FLOW_STATUS_YES)) {
            flow.setIsMake(FLOW_STATUS_YES);
        }

        //瞻仰
        if (flow.getIsAdmire().equals(FLOW_STATUS_YES)&&sysPdaFlow.getIsAdmire().equals(FLOW_STATUS_NO)) {
            flow.setIsAdmire(FLOW_STATUS_NO);
            flow.setAdmireId("");
        }else if (flow.getIsAdmire().equals(FLOW_STATUS_NO)&&sysPdaFlow.getIsAdmire().equals(FLOW_STATUS_YES)) {
            flow.setIsAdmire(FLOW_STATUS_YES);
            flow.setAdmireId(sysPdaFlow.getAdmireId());
            flow.setAdmireTimeStart(sysPdaFlow.getAdmireTimeStart());
            flow.setAdmireTimeEnd(sysPdaFlow.getAdmireTimeEnd());
        }


        if (flow.getFireType().equals(FIRE_TYPE_OTHER)&&sysPdaFlow.getFireType().equals(FIRE_TYPE_TODAY)) {
            //由择日改为当天 冰柜状态也置空
            flow.setFireType(FIRE_TYPE_TODAY);
            flow.setIsFreezer(FLOW_STATUS_NO);
            flow.setFreezerType(0);
        }else if (flow.getFireType().equals(FIRE_TYPE_TODAY)&&sysPdaFlow.getFireType().equals(FIRE_TYPE_OTHER)) {
            //由当天改为择日 新增冰柜信息 火化时间
            flow.setFireType(FIRE_TYPE_OTHER);
            flow.setIsFreezer(FLOW_STATUS_YES);
            flow.setFreezerType(sysPdaFlow.getFreezerType());
            flow.setFireTime(sysPdaFlow.getFireTime());
        }
        //修改信息
        sysPdaFlowMapper.updateById(flow);


        return true;
    }
}
